package demo.practice.leetcode_eveyday;

import java.util.*;

public class P91 {

    public static void main(String[] args) {
        P91 p91 = new P91();
        p91.numDecodings("224532656566");
    }

    public int numDecodings(String s) {
        List<String> codes = Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
                "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26");

        Set<String> set = new HashSet<>();
        codes.forEach(e -> {
            set.add(e);
        });

        if (s == null || s.length() == 0)
            return 0;

        return numDecodings(set, s);

    }

    Map<String, Integer> map = new HashMap<>();

    public int numDecodings(Set<String> set, String s) {

        if (map.get(s) != null)
            return map.get(s);

        if (s.length() == 1) {
            if (set.contains(s)) {
                map.put(s, 1);
                return 1;

            } else {
                return 0;
            }
        }

        if (s.length() == 2) {
            if (set.contains(s)) {
                map.put(s, s.equals("20") || s.equals("10") ? 1 : 2);
                return s.equals("20") || s.equals("10") ? 1 : 2;
            } else {
                if (set.contains(s.substring(0, 1)) && set.contains(s.substring(1, 2))) {
                    map.put(s,1);
                    return 1;
                } else
                    return 0;
            }
        }


        if (set.contains(s.substring(0, 1))) {
            int c1 = numDecodings(set, s.substring(1));
            if (set.contains(s.substring(0, 2)))
                c1 += numDecodings(set, s.substring(2));
            map.put(s,c1);
            return c1;
        } else {
            return 0;
        }
    }

}
